<?php

/**
 * SocialEngine
 *
 * @category   Application_Extensions
 * @package    Sitereview
 * @copyright  Copyright 2012-2013 BigStep Technologies Pvt. Ltd.
 * @license    http://www.socialengineaddons.com/license/
 * @version    $Id: AdminGeneralController.php 6590 2013-04-01 00:00:00Z SocialEngineAddOns $
 * @author     SocialEngineAddOns
 */
class Sitereview_AdminGeneralController extends Core_Controller_Action_Admin {

  //ACTION FOR MAKING THE SITEREVIEW FEATURED/UNFEATURED
  public function featuredAction() {

    $listing_id = $this->_getParam('listing_id');
    if (!empty($listing_id)) {
      $sitereview = Engine_Api::_()->getItem('sitereview_listing', $listing_id);
      $sitereview->featured = !$sitereview->featured;
      $sitereview->save();
    }
    $this->_redirect('admin/sitereview/manage');
  }

  //ACTION FOR MAKING THE SPONSORED /UNSPONSORED
  public function sponsoredAction() {

    $listing_id = $this->_getParam('listing_id');
    if (!empty($listing_id)) {
      $sitereview = Engine_Api::_()->getItem('sitereview_listing', $listing_id);
      $sitereview->sponsored = !$sitereview->sponsored;
      $sitereview->save();
    }
    $this->_redirect('admin/sitereview/manage');
  }

  //ACTION FOR MAKING THE SITEREVIEW FEATURED/UNFEATURED
  public function newlabelAction() {

    $listing_id = $this->_getParam('listing_id');
    if (!empty($listing_id)) {
      $sitereview = Engine_Api::_()->getItem('sitereview_listing', $listing_id);
      $sitereview->newlabel = !$sitereview->newlabel;
      $sitereview->save();
    }
    $this->_redirect('admin/sitereview/manage');
  }

  //ACTION FOR MAKING THE SITEREVIEW OPEN/CLOSE
  public function openCloseAction() {

    $listing_id = $this->_getParam('listing_id');
    if (!empty($listing_id)) {
      $sitereview = Engine_Api::_()->getItem('sitereview_listing', $listing_id);
      $sitereview->closed = !$sitereview->closed;
      $sitereview->save();
    }
    $this->_redirect('admin/sitereview/manage');
  }

  //ACTION FOR MAKING THE SPONSORED /UNSPONSORED
  public function sponsoredCategoryAction() {

    $category_id = $this->_getParam('category_id');
    if (!empty($category_id)) {
      $category = Engine_Api::_()->getItem('sitereview_category', $category_id);
      $category->sponsored = !$category->sponsored;
      $category->save();
    }
    $this->_redirect('admin/sitereview/settings/categories/listingtype_id/' . $category->listingtype_id);
  }

  //ACTION FOR MAKING THE SITEREVIEW APPROVE/DIS-APPROVE
  public function approvedAction() {

    $listing_id = $this->_getParam('listing_id');
    $db = Engine_Db_Table::getDefaultAdapter();
    $db->beginTransaction();
    $email = array();
    try {

      $sitereview = Engine_Api::_()->getItem('sitereview_listing', $listing_id);
      $email['subject'] = 'Approved/ Disapproved notification';
      $email['title'] = $sitereview->title;
      $owner = Engine_Api::_()->user()->getUser($sitereview->owner_id);
      $email['mail_id'] = $owner->email;
      $sitereview->approved = !$sitereview->approved;

      if (!empty($sitereview->approved)) {
        if (empty($sitereview->approved_date))
          $sitereview->approved_date = date('Y-m-d H:i:s');
        $email['message'] = "Your sitereview  \"" . $email['title'] . " \" approved ";
        Engine_Api::_()->sitereview()->aprovedEmailNotification($sitereview, $email);
      } else {
        $email['message'] = "Your sitereview " . $email['title'] . "  disapproved ";
        Engine_Api::_()->sitereview()->aprovedEmailNotification($sitereview, $email);
      }
      $sitereview->save();
      $db->commit();
    } catch (Exception $e) {
      $db->rollBack();
      throw $e;
    }
    $this->_redirect('admin/sitereview/manage');
  }

  //ACTION FOR MAKING THE SITEREVIEW APPROVE/DIS-APPROVE
  public function renewAction() {
    
    $this->_helper->layout->setLayout('admin-simple');
    $this->view->listing_id = $listing_id = $this->_getParam('listing_id');
    if ($this->getRequest()->isPost()) {
      $db = Engine_Db_Table::getDefaultAdapter();
      $db->beginTransaction();
      try {
        $sitereview = Engine_Api::_()->getItem('sitereview_listing', $listing_id);
        $sitereview->approved_date = date('Y-m-d H:i:s');
        $sitereview->save();
        $db->commit();
      } catch (Exception $e) {
        $db->rollBack();
        throw $e;
      }
      $this->_forward('success', 'utility', 'core', array(
          'smoothboxClose' => 10,
          'parentRefresh' => 10,
          'messages' => array('Renew Succesfully.')
      ));
    }
    $this->renderScript('admin-general/renew.tpl');
  }

  public function categoriesAction() {

    $element_value = $this->_getParam('element_value', 1);
    $element_type = $this->_getParam('element_type', 'listingtype_id');

    $categoriesTable = Engine_Api::_()->getDbTable('categories', 'sitereview');
    $select = $categoriesTable->select()
            ->from($categoriesTable->info('name'), array('category_id', 'category_name'))
            ->where("$element_type = ?", $element_value);

    if ($element_type == 'listingtype_id') {
      $select->where('cat_dependency = ?', 0)->where('subcat_dependency = ?', 0);
    } elseif ($element_type == 'cat_dependency') {
      $select->where('subcat_dependency = ?', 0);
    } elseif ($element_type == 'subcat_dependency') {
      $select->where('cat_dependency = ?', $element_value);
    }

    $categoriesData = $categoriesTable->fetchAll($select);

    $categories = array();
    if (Count($categoriesData) > 0) {
      foreach ($categoriesData as $category) {
        $data = array();
        $data['category_name'] = $category->category_name;
        $data['category_id'] = $category->category_id;
        $categories[] = $data;
      }
    }

    $this->view->categories = $categories;
  }

  //ACTION FOR DELETE THE LISTING
  public function deleteAction() {

    $this->_helper->layout->setLayout('admin-simple');
    $listing_id = $this->_getParam('listing_id');
    $this->view->listing_id = $listing_id;

    if ($this->getRequest()->isPost()) {
      Engine_Api::_()->getItem('sitereview_listing', $listing_id)->delete();
      $this->_forward('success', 'utility', 'core', array(
          'smoothboxClose' => 10,
          'parentRefresh' => 10,
          'messages' => array('Deleted Succesfully.')
      ));
    }
    $this->renderScript('admin-general/delete.tpl');
  }

  //ACTION FOR SHOWING LISTING TYPE MESSAGE
  public function listingTypesAction() {

    //INCREASE THE MEMORY ALLOCATION SIZE AND INFINITE SET TIME OUT
    ini_set('memory_limit', '1024M');
    set_time_limit(0);

    //GET NAVIGATION
    $this->view->navigation = Engine_Api::_()->getApi('menus', 'core')
            ->getNavigation('sitereview_admin_main', array(), 'sitereview_admin_main_listingtypes');

    $coreModuleTable = Engine_Api::_()->getDbtable('modules', 'core');
    $this->view->sitereviewlistingtypeInsalled = $coreModuleTable->hasModule('sitereviewlistingtype');
    $this->view->sitereviewlistingtypeEnabled = $coreModuleTable->isModuleEnabled('sitereviewlistingtype');

    //CREATE FORM
    $this->view->form = $form = new Sitereview_Form_Admin_Listingsettings();
    $form->removeElement('member_level');

    //GET LISTING TYPE ID AND SET OBJECT
    $this->view->listingtype_id = $listingtype_id = $this->_getParam('listingtype_id', 1);
    $this->view->listingType = $listingType = Engine_Api::_()->getItem('sitereview_listingtype', $listingtype_id);

    //SITEREVIEWLISTINGTYPE IS INSTALLED OR NOT
    $this->view->sitereviewlistingtypeEnabled = Engine_Api::_()->getDbtable('modules', 'core')->isModuleEnabled('sitereviewlistingtype');
    
    $this->view->defaultListingTypeTitle = strtolower(Engine_Api::_()->getItemTable('sitereview_listingtype')->getListingTypeColumn(1, 'title_plural'));

    $this->view->isModsSupport = Engine_Api::_()->sitereview()->isModulesSupport();
    $this->view->tab_type = 'othersettings';

    $form->populate($listingType->toArray());
    if ($listingType->language_phrases)
      $form->populate($listingType->language_phrases);
    $previous_slug_singular = $listingType->slug_singular;
    $previous_slug_plural = $listingType->slug_plural;

    if ($this->getRequest()->isPost() && $form->isValid($this->getRequest()->getPost())) {

      $slug_singular = $_POST['slug_singular'];
      $slug_plural = $_POST['slug_plural'];
      $title_singular = $_POST['title_singular'];
      $title_plural = $_POST['title_plural'];
      
      $titleSingular = $listingType->title_singular;
      $titlePlural = $listingType->title_plural;      

      if ($slug_singular == $slug_plural) {
        $error = $this->view->translate("Singular Slug and Plural Slug can't be same.");
        $error = Zend_Registry::get('Zend_Translate')->_($error);

        $form->getDecorator('errors')->setOption('escape', false);
        $form->addError($error);
        return;
      }

      if ($previous_slug_singular != $slug_singular) {
        $listingtype_id = Engine_Api::_()->getDbTable('listingtypes', 'sitereview')->checkListingSlug($slug_singular);
        if (!empty($listingtype_id)) {
          $error = $this->view->translate("Please choose the different 'Singular Slug', you have already created the same slug.");
          $error = Zend_Registry::get('Zend_Translate')->_($error);

          $form->getDecorator('errors')->setOption('escape', false);
          $form->addError($error);
          return;
        }
      }

      if ($previous_slug_plural != $slug_plural) {
        $listingtype_id = Engine_Api::_()->getDbTable('listingtypes', 'sitereview')->checkListingSlug($slug_plural);
        if (!empty($listingtype_id)) {
          $error = $this->view->translate("Please choose the different 'Plural Slug', you have already created the same slug.");
          $error = Zend_Registry::get('Zend_Translate')->_($error);

          $form->getDecorator('errors')->setOption('escape', false);
          $form->addError($error);
          return;
        }
      }
      $values = $form->getValues();
      if ($values['translation_file']) {
        $hasLanguageDirectoryPermissions = Engine_Api::_()->getApi('language', 'sitereview')->hasDirectoryPermissions();
        if (!$hasLanguageDirectoryPermissions) {
          $error = $this->view->translate("Language file for this listing type could not be overwritten. because you do not have write permission chmod -R 777 recursively to the directory '/application/languages/'. Please login in over your Cpanel or FTP and give the recursively write permission to this directory and try again.");
          $error = Zend_Registry::get('Zend_Translate')->_($error);
          $form->getDecorator('errors')->setOption('escape', false);
          $form->addError($error);
          return;
        }
      }
      $db = Engine_Db_Table::getDefaultAdapter();
      $db->beginTransaction();

      try {
        include_once APPLICATION_PATH . '/application/modules/Sitereview/controllers/license/license2.php';
        Engine_Api::_()->getApi('listingType', 'sitereview')->locationMenuUpdate($listingType);
        $listingTypeApi = Engine_Api::_()->getApi('listingType', 'sitereview');
        if ($values['pinboard_layout']) {
          $listingTypeApi->setPinBoardLayoutHomePage($listingType);
        }

        //EDIT IF SINGULAR/PLURAL TITLE HAS BEEN CHANGED
        if ($titleSingular != $listingType->title_singular || $titlePlural != $listingType->title_plural) {

          //if (!empty($_POST['pages_navigation']) && in_array('pages', $_POST['pages_navigation'])) {

            $listingTypeApi->widgetizedPagesEdit($listingType, 'home', $titleSingular, $titlePlural);
            $listingTypeApi->widgetizedPagesEdit($listingType, 'index', $titleSingular, $titlePlural);
            $listingTypeApi->widgetizedPagesEdit($listingType, 'view', $titleSingular, $titlePlural);
            $listingTypeApi->widgetizedPagesEdit($listingType, 'map', $titleSingular, $titlePlural);
          //}

          //if (!empty($_POST['pages_navigation']) && in_array('navigations', $_POST['pages_navigation'])) {

            $listingTypeApi->mainNavigationEdit($listingType);
            $listingTypeApi->gutterNavigationEdit($listingType);
          //}

          $listingTypeApi->activityFeedQueryEdit($listingType, $titleSingular, $titlePlural);
          $listingTypeApi->searchFormSettingEdit($listingType, $titleSingular, $titlePlural);
          
          //START FOR PAGE INRAGRATION.
          $sitepageintegrationEnabled = Engine_Api::_()->getDbtable('modules', 'core')->isModuleEnabled('sitepageintegration');
          if (!empty($sitepageintegrationEnabled)) {
            Engine_Api::_()->sitepageintegration()->pageintergrationTitleEdit($values['title_plural'], $this->_getParam('listingtype_id'));
          }
          //END FOR PAGE INRAGRATION.
          //START FOR BUSINESS INRAGRATION.
          $sitebusinessintegrationEnabled = Engine_Api::_()->getDbtable('modules', 'core')->isModuleEnabled('sitebusinessintegration');
          if (!empty($sitebusinessintegrationEnabled)) {
            Engine_Api::_()->sitebusinessintegration()->businessintergrationTitleEdit($values['title_plural'], $this->_getParam('listingtype_id'));
          }
          //END FOR BUSINESS INRAGRATION.
        }
        if ($values['translation_file']) {
          Engine_Api::_()->getApi('language', 'sitereview')->setTranslateForListType($listingType);
        }
        $this->view->form = $form->addNotice(Zend_Registry::get('Zend_Translate')->_('Your changes have been saved successfully.'));
        
        //BANNED PAGE URL WORK.
        $listingTypeApi->addBannedUrls($listingType);

        $db->commit();
      } catch (Exception $e) {
        $db->rollBack();
        throw $e;
      }

      $this->_redirect("admin/sitereview/general/listing-types");
    }
  }

}
